package it.koutifaris.travianmap.ui.drawhelpers.coords;

import it.koutifaris.travianmap.ui.PointToSquareHelper;
import it.koutifaris.travianmap.ui.viewstate.DynamicViewState;
import it.koutifaris.travianmap.utils.ModularBounds;

import java.util.Iterator;

import android.graphics.Canvas;
import android.graphics.Paint;

public class CoordinatesDrawerImpl implements CoordinatesDrawer {

	private final PointToSquareHelper pointToSquareHelper;
	private final ModularBounds modularBounds;
	private Canvas canvas;
	private DynamicViewState viewState;
	private int coordinateRate;

	public CoordinatesDrawerImpl(PointToSquareHelper pointToSquareHelper, ModularBounds modularBounds) {
		this.pointToSquareHelper = pointToSquareHelper;
		this.modularBounds = modularBounds;

	}

	@Override
	public void setup(Canvas canvas, DynamicViewState viewState, int coordinateRate) {
		this.canvas = canvas;
		this.viewState = viewState;
		this.coordinateRate = coordinateRate;
	}

	@Override
	public void drawXCoordinates(Iterator<Integer> xIt, Paint coordsPaint) {
		while (xIt.hasNext()) {
			int x = xIt.next();

			int colX = pointToSquareHelper.getSquareCorner(x) - viewState.getX();
			String coordTxt = String.valueOf(modularBounds.module(x));
			int textWidth = Math.round(coordsPaint.measureText(coordTxt));
			int textPos = colX + (viewState.getSquareSize() - textWidth) / 2;
			int textHeight = Math.round(coordsPaint.getTextSize());

			if (isMultipleOf(x, coordinateRate)) {
				canvas.drawText(coordTxt, textPos, textHeight, coordsPaint);
			}
		}
	}

	@Override
	public void drawYCoordinates(Iterator<Integer> yIt, Paint coordsPaint) {
		while (yIt.hasNext()) {
			int y = yIt.next();

			int colY = pointToSquareHelper.getSquareCorner(y) - viewState.getY();
			String coordTxt = String.valueOf(modularBounds.module(y));
			char[] chars = coordTxt.toCharArray();
			int textHeight = Math.round(coordsPaint.getTextSize() * chars.length);
			int textSize = Math.round(coordsPaint.getTextSize());
			int textPos = colY + textSize + (viewState.getSquareSize() - textHeight) / 2;

			if (isMultipleOf(y, coordinateRate)) {
				for (char c : chars) {
					canvas.drawText(String.valueOf(c), 0, textPos, coordsPaint);
					textPos += textSize;
				}
			}
		}
	}

	private boolean isMultipleOf(int val, int base) {
		return (val % base) == 0;
	}
}
